<?php
/**
 * @author ykm 2015-12-15
 * @describe 淘宝请求电子面单类
 */
class erpapi_logistics_matrix_taobao_request_electron extends erpapi_logistics_request_electron
{
    protected $directNum = 10;

    public function bufferRequest($sdf){
        return $this->directNum;
    }

    public function directRequest($sdf) {
        $corp = app::get('ome')->model('dly_corp')->getList('prt_tmpl_id', array('corp_id'=>$sdf['delivery'][0]['logi_id']), 0, 1);
        $templateObj = app::get("logisticsmanager")->model('express_template');
        $printTpl = $templateObj->getList('*', array('template_id'=>$corp[0]['prt_tmpl_id']), 0, 1);
        $template = $printTpl[0];
        $templateUrl = $this->_getCainiaoUrl($template);
        $this->title = '淘宝菜鸟_' . $this->__channelObj->channel['logistics_code'] . '获取电子面单';
        $this->timeOut = 6;
        $this->primaryBn = $sdf['primary_bn'];
        $arrDelivery = $sdf['delivery']; //发货单主表外，还需字段item_name、package_items、order_channels_type、order_bn
        $shop = $sdf['shop'];
        $userId = $shop['seller_id'];
        if(!$userId) {
            $userData = app::get('ome')->model('shop')->getList('addon', array('shop_id'=>$this->__channelObj->channel['shop_id']));
            $userId = $userData[0]['addon']['tb_user_id'];
        }
        $seller = array(
            'address' => array(
                'city' => $shop['city'],
                'detail' => $shop['address_detail'],
                'district' => $shop['area'],
                'province' => $shop['province'],
                #'town' => $shop['town'], //没有该字段的值
            ),
            'mobile' => $shop['mobile'],
            'name' => $shop['shop_name'],
            'phone' => $shop['tel']
        );
        $TradeOrderInfoDto = array();
        foreach($arrDelivery as $delivery) {
            $deliveryBnKey[$delivery['delivery_bn']] = $delivery;
            $arrItem = array();
            foreach($delivery['package_items'] as $pVal) {
                $arrItem[] = array(
                    'count' => $pVal['count'],
                    'name' => $pVal['item_name']
                );
            }
            $TradeOrderInfoDto[] = array(
                'object_id' => $delivery['delivery_bn'],
                'order_info' => array(
                    'order_channels_type' => $delivery['order_channels_type'],
                    'trade_order_list' => empty($delivery['order_bn']) ? $delivery['delivery_bn'] : array_unique($delivery['order_bn']),
                ),
                'package_info' => array(
                    'id' => $delivery['delivery_bn'],
                    'items' => $arrItem,
                ),
                'recipient' => array(
                    'address' => array(
                        'city' => $delivery['ship_city'],
                        'detail' => $delivery['ship_addr'],
                        'district' => $delivery['ship_district'],
                        'province' => $delivery['ship_province'],
                        #'town' => $delivery['ship_town'], //没有该字段的值
                    ),
                    'mobile' => $delivery['ship_mobile'],
                    'name' => $delivery['ship_name'],
                    'phone' => $delivery['ship_tel']
                ),
                'template_url' => $templateUrl,
                'user_id' => $userId
            );
        }
        $params = array(
            'product_code' => 'STANDARD_EXPRESS',
            'sender' => json_encode($seller),
            'trade_order_info_dtos' => json_encode($TradeOrderInfoDto),
        );
        // 超时请求3次
        $requestCount = 0;
        do {
            $result = $this->requestCall(STORE_CAINIAO_WAYBILL_I_GET, $params);
            // 判断是否请求超时
            if ($result['rsp'] != 'fail' || ($result['res_ltype'] != 1 && $result['res_ltype'] != 2) ) {
                break;
            }
            $requestCount++;
        } while ($requestCount<3);
        return $this->backToResult($result, $deliveryBnKey);
    }

    private function _getCainiaoUrl($template) {
        if(in_array($template['template_type'], array('cainiao_user', 'cainiao_standard'))) {
            $url = explode(':', $template['template_data'], 2);
        } else {
            $filter = array(
                'template_type' => 'cainiao_standard'
            );
            $logisticsTaobao = kernel::single('logisticsmanager_waybill_taobao');
            $logistics = $logisticsTaobao->logistics($this->__channelObj->channel['logistics_code']);
            $filter['template_name'] = $logistics['name'] . '菜鸟标准云模板';
            $templateObj = app::get("logisticsmanager")->model('express_template');
            $printTpl = $templateObj->getList('*', $filter, 0, 1);
            if($printTpl) {
                $url = explode(':', $printTpl[0]['template_data'], 2);
            } else {
                $url[1] = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=1001&version=38';
            }
        }
        return $url[1];
    }

    private function backToResult($ret, $deliveryBnKey){
        $data = empty($ret['data']) ? array() : json_decode($ret['data'], true);
        
        $waybill = $data['waybill_cloud_print_response'];
        if(empty($waybill)) {
            return $ret['msg'] ? $ret['msg'] : false;
        }
        $result = array();
        foreach ($waybill as $val) {
            $deliveryBn = trim($val['object_id']);
            $delivery = $deliveryBnKey[$deliveryBn];
            $printData = json_decode($val['print_data'], true);
            $position = $printData['data']['routingInfo']['sortation']['name'] . ' ' .$printData['data']['routingInfo']['routeCode'];
            $packageWdjc = $printData['data']['routingInfo']['consolidation']['name'];
            $packageWd = $printData['data']['routingInfo']['consolidation']['code'];
            $result[] = array(
                'succ' => $val['waybill_code'] ? true : false,
                'msg' => '',
                'delivery_id' => $delivery['delivery_id'],
                'delivery_bn' => $delivery['delivery_bn'],
                'logi_no' => $val['waybill_code'],
                'mailno_barcode' => '',
                'qrcode' => '',
                'position' => trim($position),
                'position_no' => '',
                'package_wdjc' => (string) $packageWdjc,
                'package_wd' => (string) $packageWd,
                'print_config' => '',
                'json_packet' => $val['print_data'],
            );
        }
        $this->directDataProcess($result);
        return $result;
    }

    public function recycleWaybill($waybillNumber) {
        
        $this->title = '淘宝菜鸟_' . $this->__channelObj->channel['logistics_code'] . '取消电子面单';
        $this->primaryBn = $waybillNumber;
        $params = array(
            'waybill_code' => $waybillNumber
        );
        $callback = array(
            'class' => get_class($this),
            'method' => 'callback'
        );
        $this->requestCall(STORE_CAINIAO_WAYBILL_CANCEL, $params, $callback);
    }

    /**
     * 获取淘宝订购地址
     *
     * @return void
     * @author 
     **/
    public function getWaybillISearch($sdf)
    {
        $params = array(
            'cp_code'    => $this->__channelObj->channel['logistics_code'],
        );

        $title = '淘宝订购地址获取';

        $result = $this->__caller->call(STORE_CN_WAYBILL_II_SEARCH,$params,array(),$title, 6, $params['cp_code']);

        if ($result['rsp'] == 'succ' && $result['data']) {
            $this->_getWISCallback($result['data']);
        }

        return array('rsp'=>$result['rsp'],'msg'=>$result['rsp']=='succ'?'获取成功':'获取失败');
    }

    private function _getWISCallback($data)
    {
        $data = json_decode($data,true);

        if (!$data) return ;

        $extendObj = app::get('logisticsmanager')->model('channel_extend');
        $shopModel = app::get('ome')->model('shop');

        $channel_id = $this->__channelObj->channel['channel_id'];
        $shop = $shopModel->dump(array('shop_id'=>$this->__channelObj->channel['shop_id']),'addon');

        // 取有面单号的
        foreach ($data['waybill_apply_subscription_info'][0]['branch_account_cols']['waybill_branch_account'] as $info) {
                $process_params = array(
                    'cancel_quantity'    => $info['cancel_quantity'],
                    'allocated_quantity' => $info['quantity'],
                    'province'           => $info['shipp_address_cols']['address_dto'][0]['province'],
                    'city'               => $info['shipp_address_cols']['address_dto'][0]['city'],
                    'area'               => $info['shipp_address_cols']['address_dto'][0]['district'],
                    'address_detail'     => $info['shipp_address_cols']['address_dto'][0]['detail'],
                    'channel_id'         => $channel_id,
                    'print_quantity'     => $info['print_quantity'],
                    'seller_id'          => $shop['addon']['tb_user_id'],
                );
                // $process_params = array(
                //     'cancel_quantity'    => $info['cancel_quantity'],
                //     'allocated_quantity' => $info['quantity'],
                //     'province'           => $info['shipp_address_cols']['waybill_address'][0]['province'],
                //     'city'               => $info['shipp_address_cols']['waybill_address'][0]['city'],
                //     'area'               => $info['shipp_address_cols']['waybill_address'][0]['area'],
                //     'address_detail'     => $info['shipp_address_cols']['waybill_address'][0]['address_detail'],
                //     'waybill_address_id' => $info['shipp_address_cols']['waybill_address'][0]['waybill_address_id'],
                //     'channel_id'         => $channel_id,
                //     'print_quantity'     => $info['print_quantity'],
                //     'seller_id'          => $info['seller_id'],   
                // );
                
                if ($info['quantity'] > 0) break;
        }

        if (!$process_params) return ;
        
        $extend = $extendObj->dump(array('channel_id'=>$channel_id),'id');
        if ($extend) $process_params['id'] = $extend['id'];

        $extendObj->save($process_params);
    }
}